package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Announcement;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private AnnouncementApi announcementApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private CommentApi commentApi;


    /**
     * 根据环信id查询用户详情信息
     * @param huanxinId
     * @return
     */
    public UserInfoVo findByHuanxin(String huanxinId) {
        //根据环信id获取用户id
        User user = userApi.findByHuanxin(huanxinId);

        //调用API获取用户详情信息
        UserInfo userInfo = userInfoApi.findById(user.getId());

        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo);

        if (userInfo.getAge() != null){
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    /**
     * 联系人添加
     * @param friendId
     */
    public void contacts(Integer friendId) {
        //将好友关系注册到环信中
        Boolean contact = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(), Constants.HX_USER_PREFIX + friendId);
        if (!contact){
            throw new BusinessException(ErrorResult.error());
        }
        //注册成功调用Api添加好友信息
        friendApi.saveFriend(Long.valueOf(friendId.toString()), UserHolder.getUserId());
    }

    /**
     * 查询联系人列表
     * @param page
     * @param pagesize
     * @param keyword
     * @return
     */
    public PageResult findAllContacts(int page, int pagesize, String keyword) {
        //获取该用户所有好友id
        List<Friend> friendList = friendApi.findByUserId(UserHolder.getUserId());

        //获取好友的id
        List<Long> friendIds = friendList.stream().map(item -> item.getFriendId()).collect(Collectors.toList());

        //根据好友id查询详情信息
        IPage<UserInfo> iPage = userInfoApi.findFriendById(friendIds,page,pagesize,keyword);

        List<UserInfo> userInfos = iPage.getRecords();
        Map<Long, UserInfo> map = CollUtil.fieldValueMap(userInfos, "id");

        List<ContactVo> contactVoList = new ArrayList<>();
        for (Friend friend : friendList) {
            UserInfo userInfo = map.get(friend.getFriendId());
            if (userInfo != null){
                ContactVo vo = ContactVo.init(userInfo);
                contactVoList.add(vo);
            }
        }
        return new PageResult(page,pagesize,Math.toIntExact(iPage.getTotal()),contactVoList);
    }

    /**
     * 查询公告列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult announcements(int page, int pagesize) {
        //调用API查询
        IPage<Announcement> iPage = announcementApi.findAll(page,pagesize);

        List<Announcement> list = iPage.getRecords();

        List<AnnouncementVo> voList = new ArrayList<>();
        for (Announcement announcement : list) {
            if (announcement != null){
                AnnouncementVo vo = AnnouncementVo.init(announcement);
                voList.add(vo);
            }
        }
        return new PageResult(page,pagesize,Math.toIntExact(iPage.getTotal()),voList);
    }

    /**
     * 用户喜欢人列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult loves(int page, int pagesize) {
        //调用APi获取喜欢的用户id
        List<Comment> commentList = commentApi.findLikes(page,pagesize, CommentType.LOVE,UserHolder.getUserId());
        return getPageResult(commentList,page,pagesize);
    }

    /**
     * 用户点赞列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult likes(int page, int pagesize) {
        //调用APi获取点赞的用户id
        List<Comment> commentList = commentApi.findLikes(page,pagesize, CommentType.LIKE,UserHolder.getUserId());
        return getPageResult(commentList,page,pagesize);
    }

    /**
     * 获取用户评论人
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult comments(int page, int pagesize) {
        //调用APi获取评论的用户id
        List<Comment> commentList = commentApi.findLikes(page,pagesize, CommentType.COMMENT,UserHolder.getUserId());
        return getPageResult(commentList,page,pagesize);
    }

    //获取comment品论或者点赞的数据
    private PageResult getPageResult(List<Comment> commentList,int page,int pagesize){
        //获取点赞用户的id
        List<Long> likeList = commentList.stream().map(item -> item.getUserId()).collect(Collectors.toList());
        //查询点赞用户的详情信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(new UserInfo(), likeList);
        //构造vo对象
        List<UserLovesVo> list = new ArrayList<>();
        for (Comment comment : commentList) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null){
                UserLovesVo vo = UserLovesVo.init(userInfo);
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(comment.getCreated())));
                list.add(vo);
            }
        }
        return new PageResult(page,pagesize,likeList.size(),list);
    }

    /**
     * 删除联系人,解除好友关系
     * @param unlikeUserId
     */
    public void deleteContacts(Long unlikeUserId) {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //解除环信关系
        Boolean contact = huanXinTemplate.deleteContact(Constants.HX_USER_PREFIX + userId, Constants.HX_USER_PREFIX + unlikeUserId);
        if (!contact){
            //解除失败抛出异常
           throw new BusinessException(ErrorResult.error());
        }
        //解除成功同时解除朋友关系表
        friendApi.deleteFriend(userId,unlikeUserId);
    }
}
